﻿namespace OnlineBookStorage
{
    using System;
    using System.Windows.Input;

    using Database;

    using FiftyNine.Ag.CommandManager.Commands;

    using Model;

    public class AddBookModel
    {
        public string Name { get; set; }

        public string Owner { get; set; }

        public string Room { get; set; }

        public string Comments { get; set; }

        private DelegateCommand add;
        private DelegateCommand cancel;

        public ICommand Add
        {
            get
            {
                return add ?? (add = new DelegateCommand(OnAdd));
            }
        }  
        
        public ICommand Cancel
        {
            get
            {
                return cancel ?? (cancel = new DelegateCommand(() => { }));
            }
        }

        private void OnAdd()
        {
            var location = DatabaseManager.Instance.FindLocationByRoom(Room);
            if (location == null)
            {
                location = DatabaseManager.Instance.AddLocation(new Location { Room = Room });
            }
            var person = DatabaseManager.Instance.FindPersonByName(Owner);
            if (person == null)
            {
                person = DatabaseManager.Instance.AddPerson(new Person() { Name = Owner });
            }
            var book = new Book { Comments = Comments, Location = location, Name = Name, Owner = person };
            DatabaseManager.Instance.AddBook(book);
        }
    }
}